package com.cysyz.web.modules.base.exceptionhandle.exceptionhandle;

import com.cysyz.json.fastjson.JSONGeneratorFastJson;
import com.cysyz.json.framework.IJsonGenerator;
import com.cysyz.json.framework.ResultType;
import com.cysyz.mylib.mailsender.SMTPMailSender;
import com.cysyz.web.modules.base.exceptionhandle.exception.AjaxOutLayerInputRuntimeException;
import com.cysyz.web.modules.base.exceptionhandle.exception.OutLayerInputRuntimeException;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 异常处理器
 */
public class ExceptionHandlerSpringMVC implements HandlerExceptionResolver {
    private Logger logger = Logger.getLogger(ExceptionHandlerSpringMVC.class);
    private SMTPMailSender mailSender;


    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception ex) {

        ModelAndView modelAndView = new ModelAndView("error");
        // 根据不同错误转向不同页面
        if(ex instanceof AjaxOutLayerInputRuntimeException) {
            IJsonGenerator jsonGenerator = new JSONGeneratorFastJson();

            List<Object> returnContent = new ArrayList<>();
            returnContent.add(ex.getMessage());
            String result = jsonGenerator.generateJSON(ResultType.FAIL, returnContent);
            response.setCharacterEncoding("UTF-8");
            try {
                response.getWriter().print(result);
            } catch (IOException e) {
                e.printStackTrace();
            }
            modelAndView = new ModelAndView();
        } else if(ex instanceof OutLayerInputRuntimeException) {
            response.setCharacterEncoding("UTF-8");
            modelAndView.addObject("errorMsg", ex.getMessage());
        } else if(ex instanceof RuntimeException) {
            ex.printStackTrace();
            logger.error(ex, ex);
            modelAndView.addObject("errorMsg", "系统发生内部错误");
        }
        return modelAndView;
    }
}
